package com.photoeditor.demo.model.filter;

import com.common.base.log.DLog;

import java.util.ArrayList;
import java.util.Random;

/**
 * 随机列表产生器
 */
public class RandomListGenerater {
    private static final String TAG = "RandomListGenerater";

    private ArrayList<Integer> mList;
    private int mCursor;

    /**
     * 决定是否重新产生随机列表，并返回下个值
     *
     * @param length
     * @return
     */
    public synchronized int next(int length) {
        if (length <= 1) {
            return 0;
        }
        if (mList == null || mCursor >= mList.size() || mList.size() != length) {
            mList = generateList(length);
            mCursor = 0;
        }
        int next = mList.get(mCursor ++);
        DLog.d(TAG, "random next: " + next);
        return next;
    }

    /**
     * 产生一个新的随机列表
     *
     * @param length
     * @return
     */
    private static ArrayList<Integer> generateList(int length) {
        ArrayList<Integer> list = new ArrayList<Integer>(length);
        for (int i = 0; i < length; i ++) {
            list.add(i);
        }
        int index;
        for (int i = length; i > 0; i --) {
            index = new Random().nextInt(i);
            list.add(list.remove(index));
        }
        DLog.d(TAG, "random list: " + list.toString());
        return list;
    }
}
